import axios from "axios";
import router from "@/router/index.js";
import Vue from "vue";

const BASE_URL = "http://localhost:8080/api";

const api = axios.create({
    baseURL: BASE_URL,
    withCredentials: false,
    timeout: 50000000
})

// 拦截器配置，如果失败就不报错，由自己逻辑处理错误的情况
api.interceptors.response.use((response) =>{
    return response;
},(err)=>{
    return err.response;
})


/**
 * 如何处理token
 */
async function tokenHandle(headers) {
    let item = localStorage.getItem("token");
    if (!item){
        router.push('/login')
    }
    headers['Authorization'] = item;
}

/**
 * 如何处理响应
 * @param response 响应体
 * @param warning 是否警告
 */
async  function responseHandle(response, warning) {
    // 警告处理
    if (warning) {
        if (response.data.code == 1) {
            // Vue.prototype.$message.warning(response.data.message);
            Vue.prototype.$message.warning(response.data.message)
            return;
        } else if (response.data.code < 0) {
            // token认证处理
            if (response.data.code == -3) {
                // Vue.prototype.$message.error("登录状态过期");
                if (!response.data.message){
                    Vue.prototype.$message.error("登录状态过期")
                }
                Vue.prototype.$message.error(response.data.message)
                return await router.push('/login')
            }
            // Vue.prototype.$message.error(response.data.message);
            Vue.prototype.$message.error(response.data.message)
            return;
        }
    }
    // token认证处理
    if (response.data.code == -3) {
        await router.push('/login')
    }
}

/**
 * 封装post请求
 * @param url 地址
 * @param params 参数
 * @param warning 是否警告
 * @param headers header
 * @param tokenNeed 是否需要token
 * @returns {Promise<any>}
 */
api.doPost = async function (url, params, warning = true, headers = {}, tokenNeed = true) {
    if (tokenNeed) {
        await tokenHandle(headers);
    }
    let response = await api.post(url, params, {headers, warning});
    await responseHandle(response, warning);
    return response.data;
}
/**
 * 封装get请求
 * @param url 地址
 * @param warning 是否警告
 * @param headers header
 * @param tokenNeed 是否需要token
 * @returns {Promise<any>}
 */
api.doGet = async function (url, warning = true, headers = {}, tokenNeed = true) {
    if (tokenNeed) {
        tokenHandle(headers)
    }
    let response = await api.get(url, {headers});
    await responseHandle(response, warning);
    return response.data;
}
/**
 * 提交表单数据
 * @param url
 * @param params
 * @param headers
 * @returns {Promise<any>}
 */
api.doPostForm = async function (url ,params,headers={}){
    let form = new FormData();
    let keys = Object.keys(params);
    for (let key of keys) {
        form.append(key,params[key]);
    }
    let response = await api.post(url, form, {headers});
    return response.data;
}

export default api;
